package ai.yue.open.service.cd.service.notify;

import ai.yue.library.base.crypto.client.SecureCommon;
import ai.yue.library.base.util.DateUtils;
import ai.yue.open.service.cd.entity.ConfNotify;
import ai.yue.open.service.cd.entity.Workload;
import ai.yue.open.service.cd.service.ConfNotifyService;
import cn.hutool.core.util.StrUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Rancher CD
 * 
 * @author	ylyue
 * @since	2018年11月12日
 */
@Service
@RequiredArgsConstructor
public class NotifyDingTalkService {

    @Value("${spring.application.name}")
    String applicationName;
    final ConfNotifyService confNotifyService;

    /**
     * 钉钉发送链接消息
     */
    public OapiRobotSendResponse sendLinkMessage(String workloadApiUrl, Workload workload, String imageTag) {
        // 1. 初始化链接消息
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("link");
        OapiRobotSendRequest.Link link = new OapiRobotSendRequest.Link();

        // 2. 组装消息体
        String workloadUrl = workloadApiUrlToWorkloadUrl(workloadApiUrl);
        String dateTime = DateUtils.getDatetimeFormatter();
        link.setMessageUrl(workloadUrl);
        link.setPicUrl("");
        link.setTitle("Rancher DevOps");
        link.setText(
                dateTime + "\n哇哦...工作负载【" + workload.getNamespace() + ":" + workload.getWorkloadName() + ":" + imageTag + "】正在升级，赶快看看吧！"
        );
        request.setLink(link);

        // 3. 发送消息
        return sendRequest(request);
    }

    /**
     * 钉钉发送文本消息
     */
    public OapiRobotSendResponse sendTextMessage(String workloadApiUrl, Workload workload, String imageTag) {
        // 1. 初始化文本消息
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();

        // 2. 组装消息体
        String workloadUrl = workloadApiUrlToWorkloadUrl(workloadApiUrl);
        ConfNotify confNotify = confNotifyService.list().get(0);
        String yueOpenDevopsDeployAdminUrl = confNotify.getYueOpenDevopsDeployAdminUrl();
        String dateTime = DateUtils.getDatetimeFormatter();
        text.setContent(
                dateTime
                        + "\n警告...警告！工作负载【" + workload.getNamespace() + ":" + workload.getWorkloadName() + ":" + imageTag + "】升级失败...\n"
                        + "请点击以下链接检查 " + applicationName + " 部署日志：\n"
                        + yueOpenDevopsDeployAdminUrl + "\n"
                        + "若需要手动进行工作负载升级，请访问如下地址：\n"
                        + workloadUrl + "\n"
        );
        request.setText(text);

        // 3. 设置@人
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        List<String> atMobiles = confNotify.getDingtalkAtMobiles();
        at.setAtMobiles(atMobiles);
        request.setAt(at);

        // 4. 发送消息
        return sendRequest(request);
    }

    /**
     * 发送钉钉请求
     */
    private OapiRobotSendResponse sendRequest(OapiRobotSendRequest request) {
        OapiRobotSendResponse oapiRobotSendResponse = null;
        try {
            ConfNotify confNotify = confNotifyService.list().get(0);
            String dingtalkDevopsRobotWebhook = confNotify.getDingtalkDevopsRobotWebhook();
            String dingtalkDevopsRobotSignSecret = confNotify.getDingtalkDevopsRobotSignSecret();
            
			DingTalkClient dingTalkClient;
			if (StrUtil.isNotEmpty(dingtalkDevopsRobotSignSecret)) {
				dingTalkClient = new DefaultDingTalkClient(SecureCommon.dingtalkRobotSign(dingtalkDevopsRobotWebhook, dingtalkDevopsRobotSignSecret));
			} else {
				dingTalkClient = new DefaultDingTalkClient(dingtalkDevopsRobotWebhook);
			}

			oapiRobotSendResponse = dingTalkClient.execute(request);
        } catch (ApiException e) {
            e.printStackTrace();
        }

        return oapiRobotSendResponse;
    }

    private String workloadApiUrlToWorkloadUrl(String workloadApiUrl) {
        String rancherWorkloadUrl = workloadApiUrl.replaceFirst("k8s/clusters", "dashboard/c");
        return StrUtil.subBefore(rancherWorkloadUrl, "v1", false) + "explorer/workload";
    }

}
